from dbutils.pooled_db import PooledDB
import mysql.connector
import logging

class DatabaseConnectionPool:
    pool = None

    @staticmethod
    def get_pool():
        if DatabaseConnectionPool.pool is None:
            DatabaseConnectionPool.pool = PooledDB(
                mysql.connector,  # 数据库驱动
                mincached=2,  # 初始化时建立的最小连接数
                maxcached=10,  # 最大连接数
                host="121.199.60.228",
                user="root",
                password="1234",
                database="traffic"
            )
        return DatabaseConnectionPool.pool

    @staticmethod
    def get_connection():
        pool = DatabaseConnectionPool.get_pool()
        try:
            conn = pool.connection()
            return conn
        except mysql.connector.Error as err:
            logging.error(f"数据库连接失败: {err}")
            return None

    @staticmethod
    def close_connection(connection):
        if connection:
            connection.close()
            logging.info("数据库连接已关闭并归还给连接池。")